<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/9/18 16:59
 */

namespace module\user\logic;

use module\user\model\InviteLog;
use module\user\model\User;
use mof\annotation\Inject;
use mof\exception\LogicException;
use mof\interface\UserInterface;
use mof\Logic;

class InviteLogic extends Logic
{
    #[Inject(InviteLog::class)]
    protected $model;

    /**
     * 新增邀请记录
     * @param User $inviterUser
     * @param UserInterface|User $inviteeUser 被邀请人
     * @return InviteLog
     */
    public function createLog(User $inviterUser, UserInterface|User $inviteeUser): InviteLog
    {
        //奖励邀请人
        if (!app()->config->get('user.invite_enabled')) {
            throw new LogicException('邀请功能已关闭');
        } elseif ($inviterUser->id === $inviteeUser->id) {
            throw new LogicException('不能邀请自己');
        }

        //记录邀请人
        $inviteeUser->save(['inviter_id' => $inviterUser->id]);

        $awardScore = (int)app()->config->get('user.invite_reward', 0);
        if ($awardScore > 0) {
            app(UserLogic::class)->withUser($inviterUser)->addScore(
                $awardScore, 'invite', '邀请奖励'
            );
        }
        $model = new InviteLog();
        $model->save([
            'inviter_id'  => $inviterUser->id,
            'invitee_id'  => $inviteeUser->id,
            'award_score' => $awardScore,
        ]);
        return $model;
    }
}